import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Tabs, Tag, Space, Spin, message, Modal, Form, Input, Typography } from 'antd';
import { EditOutlined, BookOutlined, InfoCircleOutlined, PlayCircleOutlined, TeamOutlined, TrophyOutlined } from '@ant-design/icons';
import { contestService } from '@/services/contestService';
import { Contest, ContestRuleType, ContestStatus, ContestType, ContestParticipant } from '@/types/contest';
import { Problem } from '@/types/problem';
import styles from './Detail.module.css';

import { 
  ContestDescription,
  ContestProblems,
  ContestInfo,
  ContestParticipants,
  ContestRanking,
  ContestCountdown
} from './components';

const { Title } = Typography;

interface ContestDetailProps {
  isAdmin?: boolean;
}

const ContestDetail: React.FC<ContestDetailProps> = ({ isAdmin = false }) => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [contest, setContest] = useState<Contest | null>(null);
  const [problems, setProblems] = useState<Problem[]>([]);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [passwordForm] = Form.useForm();
  const [loadingProblems, setLoadingProblems] = useState(false);
  const [participants, setParticipants] = useState<ContestParticipant[]>([]);
  const [loadingParticipants, setLoadingParticipants] = useState(false);
  const [isParticipant, setIsParticipant] = useState(false);
  const [checkingParticipation, setCheckingParticipation] = useState(false);
  const [joinModalVisible, setJoinModalVisible] = useState(false);
  const [leftActiveTab, setLeftActiveTab] = useState("description");
  const [rightActiveTab, setRightActiveTab] = useState("info");

  const urlPrefix = isAdmin ? '/admin/contest' : '/contest';

  useEffect(() => {
    if (id) {
      fetchContest();
      //fetchProblems();
      checkParticipation();
    }
  }, [id]);

  const fetchContest = async () => {
    try {
      setLoading(true);
      const response = await contestService.getContest(Number(id));
      setContest(response.data.data);
      //fetchParticipants();
    } catch (error: any) {
      if (error.response?.data?.message === "This contest requires password verification") {
        setPasswordModalVisible(true);
      } else {
        message.error('获取比赛详情失败');
      }
    } finally {
      setLoading(false);
    }
  };

  // 检查是否已参加比赛
  const checkParticipation = async () => {
    if (!id) return;
    
    try {
      setCheckingParticipation(true);
      const response = await contestService.checkParticipation(Number(id));
      const { has_participated } = response.data.data;
      setIsParticipant(has_participated);
    } catch (error: any) {
      console.error('检查参与状态失败:', error);
      // 如果检查失败，默认设置为未参与状态
      setIsParticipant(false);
    } finally {
      setCheckingParticipation(false);
    }
  };

  const handleVerifyPassword = async () => {
    try {
      await passwordForm.validateFields();
      const values = passwordForm.getFieldsValue();
      
      await contestService.verifyPassword(Number(id), { password: values.password });
      message.success('密码验证成功');
      setPasswordModalVisible(false);
      fetchContest();
      // 重新检查参与状态
      await checkParticipation();
    } catch (error: any) {
      if (error.response?.data?.message === "Wrong password") {
        message.error('密码错误');
      } else if (!error.response) {
        // Form validation error, do nothing
      } else {
        message.error('验证失败');
      }
    }
  };

  // 加入比赛
  const handleJoinContest = async () => {
    if (!id) return;

    try {
      if (contest?.contest_type === 'Password Protected') { // 密码保护比赛
        setJoinModalVisible(true);
      } else { // 公开比赛
        await joinContest();
      }
    } catch (error) {
      message.error('加入比赛失败');
    }
  };

  // 提交比赛密码并加入
  const handleJoinWithPassword = async () => {
    try {
      await passwordForm.validateFields();
      const values = passwordForm.getFieldsValue();
      
      await contestService.verifyPassword(Number(id), { password: values.password });
      await joinContest();
      setJoinModalVisible(false);
      // 重新检查参与状态
      await checkParticipation();
    } catch (error: any) {
      if (error.response?.data?.message === "Wrong password") {
        message.error('密码错误');
      } else if (!error.response) {
        // Form validation error, do nothing
      } else {
        message.error('验证失败');
      }
    }
  };

  // 实际加入比赛的逻辑
  const joinContest = async () => {
    try {
      // 这里应该调用加入比赛的API
      // 简化版本，我们使用验证密码的API表示加入成功
      await contestService.verifyPassword(Number(id), { password: '' });
      message.success('成功加入比赛');
      // 重新检查参与状态以确保同步
      await checkParticipation();
      // 刷新参与者列表
      //fetchParticipants();
    } catch (error) {
      message.error('加入比赛失败');
    }
  };

  const getStatusTag = (status: ContestStatus | undefined) => {
    const statusMap: Record<ContestStatus, { color: string; text: string }> = {
      '1': { color: 'blue', text: '未开始' },
      '0': { color: 'green', text: '进行中' },
      '-1': { color: 'gray', text: '已结束' }
    };
    
    if (!status || !statusMap[status as ContestStatus]) {
      return <Tag color="default">未知</Tag>;
    }
    
    return (
      <Tag color={statusMap[status as ContestStatus].color}>
        {statusMap[status as ContestStatus].text}
      </Tag>
    );
  };

  const getRuleTypeTag = (ruleType: ContestRuleType | undefined) => {
    const ruleTypeMap: Record<ContestRuleType, { color: string; text: string }> = {
      'ACM': { color: 'red', text: 'ACM' },
      'OI': { color: 'purple', text: 'OI' }
    };
    
    if (!ruleType || !ruleTypeMap[ruleType as ContestRuleType]) {
      return <Tag color="default">未知</Tag>;
    }
    
    return (
      <Tag color={ruleTypeMap[ruleType as ContestRuleType].color}>
        {ruleTypeMap[ruleType as ContestRuleType].text}
      </Tag>
    );
  };

  const getContestTypeTag = (contestType: ContestType | undefined) => {
    const contestTypeMap: Record<ContestType, { color: string; text: string }> = {
      'Public': { color: 'green', text: '公开比赛' },
      'Password Protected': { color: 'orange', text: '密码保护' }
    };
    
    if (!contestType || !contestTypeMap[contestType as ContestType]) {
      return <Tag color="default">未知</Tag>;
    }
    
    return (
      <Tag color={contestTypeMap[contestType as ContestType].color}>
        {contestTypeMap[contestType as ContestType].text}
      </Tag>
    );
  };


  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin>
          <div style={{ padding: '50px', background: 'rgba(0, 0, 0, 0.05)' }}>
            <div style={{ textAlign: 'center', marginBottom: '20px' }}>加载中...</div>
          </div>
        </Spin>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      {contest && (
        <div className={styles.contentLayout}>
          {/* 左侧栏 - 比赛描述和题目Tab */}
          <div className={styles.leftColumn}>
            <Card className={styles.leftCard}>
              <div className={styles.contestHeader}>
                <div className={styles.titleRow}>
                  <Title level={3}>{contest.title}</Title>
                  <div className={styles.titleRight}>
                    <ContestCountdown 
                      startTime={contest.start_time}
                      endTime={contest.end_time}
                      status={contest.status}
                    />
                    {isAdmin && (
                      <Button 
                        type="primary" 
                        icon={<EditOutlined />}
                        onClick={() => navigate(`${urlPrefix}/edit/${id}`)}
                      >
                        编辑比赛
                      </Button>
                    )}
                  </div>
                </div>
                <div>
                  <Space size="middle">
                    {getStatusTag(contest.status)}
                    {getRuleTypeTag(contest.rule_type)}
                    {getContestTypeTag(contest.contest_type)}
                  </Space>
                </div>
              </div>
              
              <Tabs
                activeKey={leftActiveTab}
                onChange={setLeftActiveTab}
                className={styles.leftTabs}
                items={[
                  {
                    key: "description",
                    label: <span><InfoCircleOutlined /> 比赛描述</span>,
                    children: <ContestDescription contest={contest} />
                  },
                  {
                    key: "problems",
                    label: <span><BookOutlined /> 比赛题目</span>,
                    children: <ContestProblems 
                      isAdmin={isAdmin} 
                      isParticipant={isParticipant} 
                      contestStatus={contest.status}
                    />
                  },
                  {
                    key: "ranking",
                    label: <span><TrophyOutlined /> 排行榜</span>,
                    children: <ContestRanking contest={contest} />
                  }
                ]}
              />
            </Card>
          </div>

          {/* 右侧栏 - 操作按钮和比赛详情、参与者Tab */}
          <div className={styles.rightColumn}>
            {/* 操作按钮 */}
            <div className={styles.actionButtons}>
              {checkingParticipation ? (
                <Button 
                  type="default" 
                  size="large"
                  className={styles.actionButton}
                  loading
                >
                  检查参与状态...
                </Button>
              ) : isParticipant ? (
                <Button 
                  type="primary" 
                  icon={<PlayCircleOutlined />} 
                  size="large"
                  className={styles.actionButton}
                  onClick={() => setLeftActiveTab("problems")}
                >
                  开始答题
                </Button>
              ) : (
                <Button 
                  type="primary" 
                  icon={<TeamOutlined />} 
                  size="large"
                  className={styles.actionButton}
                  onClick={handleJoinContest}
                  disabled={contest.status === '-1'}
                >
                  参加比赛
                </Button>
              )}
            </div>

            {/* 比赛详情和参与者Tab */}
            <Card className={styles.rightCard}>
              <Tabs 
                activeKey={rightActiveTab}
                onChange={setRightActiveTab}
                className={styles.rightTabs}
                items={[
                  {
                    key: "info",
                    label: <span><InfoCircleOutlined /> 比赛信息</span>,
                    children: <ContestInfo contest={contest} />
                  },
                  {
                    key: "participants",
                    label: <span><TeamOutlined /> 参赛者</span>,
                    children: <ContestParticipants isAdmin={isAdmin} />
                  }
                ]}
              />
            </Card>
          </div>
        </div>
      )}

      {/* 密码验证对话框 */}
      <Modal
        title="请输入比赛密码"
        open={passwordModalVisible}
        onOk={handleVerifyPassword}
        onCancel={() => navigate(`${urlPrefix}/list`)}
      >
        <Form form={passwordForm}>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入比赛密码' }]}
          >
            <Input.Password placeholder="请输入比赛密码" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 加入比赛密码对话框 */}
      <Modal
        title="请输入比赛密码"
        open={joinModalVisible}
        onOk={handleJoinWithPassword}
        onCancel={() => setJoinModalVisible(false)}
      >
        <Form form={passwordForm}>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入比赛密码' }]}
          >
            <Input.Password placeholder="请输入比赛密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ContestDetail; 